<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>宿舍管理系统</title>
    <meta name="renderer" content="webkit">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="stylesheet" href="{{ asset('css/font.css') }}">
    {{-- <link rel="stylesheet" href="{{asset('lib/layui/css/layui.css')}}"> --}}
    <link rel="stylesheet" href="{{ asset('css/xadmin.css') }}">
    <script src="{{ asset('lib/layui/layui.js') }}" charset="utf-8"></script>
    <script type="text/javascript" src="{{ asset('js/xadmin.js') }}"></script>

    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="/home">首页</a>
            <a>
                <cite>人员列表</cite></a>
        </span>
        <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
            onclick="location.reload()" title="刷新">
            <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
    </div>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-body ">
                        <form class="layui-form layui-col-space5">
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="name" placeholder="请输入姓名" autocomplete="off"
                                    class="layui-input" value="{{ old('name') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="id_card" placeholder="请输入身份证" autocomplete="off"
                                    class="layui-input" value="{{ old('id_card') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="card_num" placeholder="请输入工号" autocomplete="off"
                                    class="layui-input" value="{{ old('card_num') }}">
                            </div>
                            <div class="layui-input-inline layui-show-xs-block">
                                <select name="department_id" lay-search>
                                    <option value="" {{ old('department_id') ? '' : 'selected' }}>部门</option>
                                    @foreach ($departments as $dept)
                                        <option value="{{ $dept->id }}"
                                            {{ old('department_id') == $dept->id ? 'selected' : '' }}>
                                            {{ $dept->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="layui-input-inline layui-show-xs-block">
                                <select name="staff_position_id">
                                    <option value="" {{ old('staff_position_id') ? '' : 'selected' }}>职务</option>
                                    @foreach ($staffPositions as $po)
                                        <option value="{{ $po->id }}"
                                            {{ old('staff_position_id') == $po->id ? 'selected' : '' }}>
                                            {{ $po->position }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="layui-input-inline layui-show-xs-block">
                                <select name="dorm.building_id">
                                    <option value="" {{ old('dorm.building_id') ? '' : 'selected' }}>楼栋</option>
                                    @foreach ($buildings as $building)
                                        <option value="{{ $building->id }}"
                                            {{ old('dorm.building_id') == $building->id ? 'selected' : '' }}>
                                            {{ $building->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <input type="text" name="dorm.code" placeholder="请输入宿舍号" autocomplete="off"
                                    class="layui-input" value="{{ old('dorm.code') }}">
                            </div>
                            <div class="layui-inline layui-show-xs-block">
                                <button class="layui-btn" id="btn-search"><i class="layui-icon">&#xe615;</i></button>
                            </div>
                        </form>
                    </div>
                    <div class="layui-card-body layui-table-body layui-table-main">
                        <table class="layui-hide" id="test" lay-filter="test"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<script type="text/html" id="barDemo">
    @{{# if(d.status==="在职") { }}
        @{{# if(d.dorm_id) { }}
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="replace_dorm">更换宿舍</a>
            <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="add_family">添加家属</a>
        @{{# }else{ }}
            <a class="layui-btn layui-btn-xs" lay-event="set_dorm">安排宿舍</a>
        @{{# } }}
    @{{# } }}
</script>

<button id="importExcel" style="display: none;"></button>
<input type="hidden" name="_token" class="tag_token" value="{{ csrf_token() }}">
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
            <i class="layui-icon">&#xe654;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="update">
            <i class="layui-icon">&#xe642;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">
            <i class="layui-icon">&#xe640;</i>
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="export" >
            <i class="layui-icon">&#xe67d;全部导出</i>
        </button>
        <button  class="layui-btn layui-btn-primary layui-btn-sm" lay-event="download" >
            <i class="layui-icon">&#xe601;下载模板</i>
        </button>
        <button  class="layui-btn layui-btn-primary layui-btn-sm" lay-event="upload" >
            <i class="layui-icon">&#xe681;导入员工</i>
        </button>
    </div>
</script>
<script>
    layui.use(['table', 'upload', 'jquery'], function() {
        var upload = layui.upload;
        let $ = layui.jquery;
        var layer = layui.layer;
        var uploadInst = upload.render({
            elem: '#importExcel' //绑定元素
                ,
            url: '/staffs/import/excel' //上传接口
                ,
            accept: 'file',
            exts: 'xls|xlsx',
            data: {
                '_token': $(".tag_token").val()
            },
            done: function(res) {
                layer.closeAll('loading');
                if (res.code == 0) {
                    layer.msg(res.msg, {
                        time: 3000, //6s后自动关闭
                        icon: 1
                    });
                } else {
                    layer.msg(res.msg, {
                        time: 3000, //6s后自动关闭
                        icon: 2
                    });
                }
            },
            error: function(err) {
                console.log(err)
                //请求异常回调
            }
        });

        var table = layui.table;
        let b = build_criteria();
        let q = asm_query(b)
        let total = 0;
        let t_export = table.render({
            elem: '#test',
            url: `/staffs?${q}`,
            toolbar: '#toolbarDemo',
            title: '人员列表',
            cols: [
                [{
                    type: 'checkbox'
                }, {
                    field: 'id',
                    title: 'ID',
                    width: 80,
                    unresize: true,
                    hide: true
                }, {
                    field: 'company.name',
                    title: '公司',
                    width: 100,
                    templet: function(d) {
                        return d.company.short_name || d.company.name;
                    },
                    hide: {{ Auth::user()->is_super ? 'false' : 'true' }}
                }, {
                    field: 'name',
                    title: '姓名',
                    width: 80,
                    sort: true
                }, {
                    field: 'card_num',
                    title: '工号',
                    width: 100,
                    sort: true
                }, {
                    field: 'id_card',
                    title: '身份证',
                    width: 160,
                    sort: true
                }, {
                    field: 'age',
                    title: '年龄',
                    width: 80,
                    sort: true
                }, {
                    field: 'sex',
                    title: '性别',
                    width: 80,
                    sort: true
                }, {
                    field: 'department_name',
                    title: '部门',
                    width: 120,
                    sort: true
                }, {
                    field: 'position',
                    title: '职位',
                    width: 100,
                    sort: true
                }, {
                    field: 'date_enroll',
                    title: '入职日期',
                    width: 100,
                    sort: true
                }, {
                    field: 'work_years',
                    title: '工龄',
                    width: 60,
                    sort: true
                }, {
                    field: 'building_name',
                    title: '楼栋',
                    width: 100
                }, {
                    field: 'dorm_code',
                    title: '宿舍',
                    width: 100,
                    sort: true
                }, {
                    field: 'latest_in_date',
                    title: '入住日期',
                    width: 100,
                    sort: true
                }, {
                    field: 'families_count',
                    title: '家属',
                    width: 60
                }, {
                    field: 'status',
                    title: '状态',
                    width: 80,
                    sort: true
                }, {
                    field: 'phone',
                    title: '手机',
                    width: 120,
                    sort: true
                }, {
                    field: 'remark',
                    title: '备注',
                    width: 100
                }, {
                    field: 'created_at',
                    title: '创建时间',
                    width: 150,
                    sort: true
                }, {
                    field: 'updated_at',
                    title: '更新时间',
                    width: 150,
                    sort: true
                }, {
                    fixed: 'right',
                    title: '操作',
                    width: 240,
                    align: 'center',
                    toolbar: '#barDemo'
                }]
            ],
            autoSort: true,
            initSort: {
                field: 'updated_at',
                type: 'desc'
            },
            page: true,
            limit: 20,
            limits: [20, 40, 80, 160, 320, 640, 1280],
            parseData: function(res) { //将原始数据解析成 table 组件所规定的数据
                total = res.data.meta.pagination.total;
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": total, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            }
        });




        //监听头工具栏事件
        table.on('toolbar(test)', function(obj) {
            let checkStatus = table.checkStatus(obj.config.id);
            let data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    xadmin.open('添加人员', '{{ route('staffs.create') }}')
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        xadmin.open('更新人员', `/staffs/${data[0].id}/edit`);
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        layer.confirm('确认要删除吗？', function(index) {
                            //发异步删除数据
                            data.forEach(t => {
                                del_one(null, t.id);
                            });
                            layer.close(index);
                            table.reload('test', {});
                        });
                    }
                    break;
                case 'export':
                    //使用ajax请求获取所有数据
                    layer.load();
                    $.ajax({
                        url: "/staffs?export=2",
                        type: 'get',
                        dataType: 'json',
                        success: function(res) {
                            //使用table.exportFile()导出数据
                            table.exportFile(t_export.config.id, res.data.data, 'xls');
                        },
                        complete: function() {
                            layer.closeAll('loading');
                        }
                    });
                    break;
                case 'upload':
                    //执行实例
                    layer.load();
                    $('#importExcel').click()
                    break;
                case 'download':
                    window.open('/staffs/download/excel')
                    break;
            };
        });



        //监听行事件
        table.on('tool(test)', function(obj) {
            let data = obj.data; //获得当前行数据
            let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            let url = `/staffs/${data.id}/dorm-arrange`;
            let staff_info = `${data.department_name||''} ${data.position||''} ${data.name}`;
            let title = "";
            switch (layEvent) {
                case 'set_dorm':
                    title = `${staff_info} 宿舍安排`;
                    xadmin.open(title, url)
                    break;
                case 'replace_dorm':
                    title = `${staff_info} 宿舍调整`;
                    xadmin.open(title, url)
                    break;
                case 'add_family':
                    xadmin.open(staff_info + ' 添加家属', '/families/create?staff_id=' + data.id)
                    break;
            }

        });

        $('#btn-search').click(
            function() {
                b = build_criteria();
                q = asm_query(b)
                table.reload('test', {
                    url: '/staffs',
                    where: {
                        search: b.criteria,
                        searchJoin: 'and'
                    },
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                });
                return false;
            }
        );

    });

    /*类型-删除*/
    function type_del(obj, id) {
        layer.confirm('确认要删除吗？', function(index) {
            //发异步删除数据
            del_one(obj, id);
        });
    }


    function build_criteria() {
        let staff_name = $("[name='name']").val();
        let card_num = $("[name='card_num']").val();
        let id_card = $("[name='id_card']").val();
        let dept_id = $("[name='department_id']").val();
        let position_id = $("[name='staff_position_id']").val();
        let building_id = $("[name='dorm.building_id']").val();
        let dorm_code = $("[name='dorm.code']").val();
        let criteria = '';
        let oprt = '';
        if (staff_name)
            criteria += `name:${staff_name};`;
        if (id_card) {
            criteria += `id_card:${id_card};`;
        }
        if (card_num) {
            criteria += `card_num:${card_num};`;
        }
        if (dept_id)
            criteria += `department_id:${dept_id};`;
        if (position_id)
            criteria += `staff_position_id:${position_id};`
        if (building_id) {
            criteria += `dorm.building_id:${building_id};`
        }
        if (dorm_code) {
            criteria += `dorm.code:${dorm_code};`
        }

        if (criteria)
            criteria = criteria.slice(0, -1);
        return {
            criteria,
            oprt
        }
    }

    function asm_query(build_criteria, order = 'updated_at', sort = 'desc') {
        return `search=${build_criteria.criteria}&searchFields=${build_criteria.oprt}&searchJoin=and&orderBy=${order}&sortedBy=${sort}`
    }

    function del_one(obj, id) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: 'staffs/' + id,
            type: 'DELETE',
            dataType: "json",
            success: function(res) {
                if (res.error) {
                    layer.msg('删除失败:' + res.message, {
                        icon: 2,
                        time: 3000
                    });
                } else {
                    layer.msg(`已删除${id}!`, {
                        icon: 1,
                        time: 1000
                    });
                }

            },
            error: function(err) {
                layer.msg('删除失败', {
                    icon: 2,
                    time: 1000
                });
            }
        });
    }

    function delAll(argument) {
        let ids = [];
        let inputs = [];
        // 获取选中的id
        $('tbody input').each(function(index, el) {
            if ($(this).prop('checked')) {
                ids.push($(this).val());
                inputs.push(this);
            }
        });

        if (ids.length > 0) {
            layer.confirm('确认要删除吗？' + ids.toString(), function(index) {
                //捉到所有被选中的，发异步进行删除
                // layer.msg('删除成功', {icon: 1});
                // $(".layui-form-checked").not('.header').parents('tr').remove();
                ids.forEach((id, idx) => {
                    del_one(inputs[idx], id);
                });
            });
        }
    }
</script>

</html>
